<template>
	<view>
		<waterfall-flow2 ref="waterfallFlow" offset="10rpx" :list="list" @load="waterfallFlowLoad">
			<template v-slot:left="{leftList}">
				<view class="item-warter" v-for="(item, index) in leftList" :key="index" @click="e => clickItem(item)">
					<image mode="widthFix" :src="item.url" :lazy-load="true"></image>
					<view class="text-break-all">{{ item.title }}</view>
				</view>
			</template>
			<template v-slot:right="{rightList}">
				<view class="item-warter" v-for="(item, index) in rightList" :key="index" @click="e => clickItem(item)">
					<image mode="widthFix" :src="item.url" :lazy-load="true"></image>
					<view class="text-break-all">{{ item.title }}</view>
				</view>
			</template>
		</waterfall-flow2>
	</view>
</template>

<script>
import waterfallFlow2 from '@/components/waterfall-flow2.vue';

export default {
	components: {
		waterfallFlow2
	},
	data() {
		return {
			list: [], // PS: 直接写死在这里瀑布流并不会渲染，因为内部是watch监听渲染的，需要在其他地方被赋值，如onLoad
			count: 0
		}
	},
	onLoad() {
		this.getList();
	},
	methods: {
		// 获取数据
		getList() {
			const tem = [];
			for (let i = 0; i < 10; i++) {
				this.count++
				const height = this.randomAccess(200, 600);
				const url = `https://picsum.photos/id/${this.count}/200/${height}`
				const title = this.getRandomName(height / 2 / 2 / 2);
				tem.push({ url, title, id: this.count }); // 之前声明tem忘记使用了，应该改成这样写，不要在for里面给data赋值哦！！
			};
			this.list = this.list.concat(tem);
		},
		// 生成一定范围内的随机数
		randomAccess(min, max) {
			return Math.floor(Math.random() * (min - max) + max)
		},
		// 解码
		decodeUnicode(str) {
			str = "\\u" + str;
			str = str.replace(/\\/g, "%");
			str = unescape(str);
			str = str.replace(/%/g, "\\");
			return str;
		},
		// 随机生成汉字
		getRandomName(NameLength) {
			let name = "";
			for (let i = 0; i < NameLength; i++) {
				let unicodeNum  = "";
				unicodeNum = this.randomAccess(0x4e00, 0x9fa5).toString(16);
				name += this.decodeUnicode(unicodeNum);
			};
			return name;
		},
		// 元素项被点击
		clickItem(item) {
			// 可做页面跳转等
			console.log("点击了：", item);
		},
		// 瀑布流列表渲染完毕
		waterfallFlowLoad(event) {
			console.log("渲染完成：", event);
		}
	},
	// 页面触底事件，加载下一页
	onReachBottom() {
		this.getList();
	},
	// 下拉刷新
	onPullDownRefresh() {
		this.list = [];
		/** 
		 * 数据被置空时，this.$refs.waterfallFlow.clear()方法是必须要调的
		 * 如果是强制渲染的场景请使用this.$refs.waterfallFlow.update(), 例如排序
		 * */
		this.$refs.waterfallFlow.clear();
		
		setTimeout(() => {
			this.getList();
			uni.stopPullDownRefresh();
		}, 500);
	}
}
</script>

<style>
page {
	background-color: #f8f8f8;
}
</style>
<style scoped>
.item-warter {
	width: 100%;
	height: auto;
	background-color: #ffaaff;
	border-radius: 10rpx;
	overflow: hidden;
}

/* PS: 快手小程序不支持该选择器，在template中用js判断加上边距 */
.item-warter:nth-child(n+2) {
	margin-top: 10rpx;
}

.item-warter image {
	width: 100%;
}

.text-break-all {
	word-break: break-all;
}
</style>